package com.ark.frigate.zookeeper.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.springframework.util.Assert;

/**
 * 非公平锁
 *
 * @author zengweilong
 * @date 9/28/21 3:36 PM
 */
@Slf4j
public class ZookeeperUnFairLock {

    private CuratorFramework curatorFramework;

    private String lockPath;


    public ZookeeperUnFairLock(String lockPath) {
        Assert.isTrue(StringUtils.isNotBlank(lockPath), "lock path is required.");
        this.lockPath = lockPath;
    }

    public boolean lock() {
        this.curatorFramework = SpringUtils.getBean(CuratorFramework.class);
        try {
            curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(lockPath);
            return true;
        } catch (Exception e) {
            log.error("get lock fail = ", e);
            return false;
        }
    }

    public boolean unLock() {
        try {
            curatorFramework.delete().forPath(lockPath);
            log.info("unlock key={}", lockPath);
            return true;
        } catch (Exception e) {
            log.error("UnLock fail.", e);
            return false;
        }
    }

}
